package com.listen.service.DB;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.listen.common.DateFormatUtil;
import com.listen.common.HttpClientProxy;
import com.listen.common.IPProxyNew;
import com.listen.common.SpecialCharacterHandler;
import com.listen.common.StringUtil;
import com.listen.model.Study;
import com.listen.model.User;
import com.listen.vo.HeadParmsVO;

import net.sf.json.JSONObject;

/**
 * 八大员听课
 * @author ibm
 *
 */
public class BadayuanNewProxy{
	private static final Logger log = LoggerFactory.getLogger(BadayuanNewProxy.class);
	private ConcurrentHashMap<String, Object>  resultMap = null;
	private HttpClientProxy instance = new HttpClientProxy();
	private CloseableHttpResponse response = null;
	private CloseableHttpClient httpClient = null;
	private String proxyInfo = null;
	
	public static void main(String args[]) throws InterruptedException{
		IPProxyNew proxy = new IPProxyNew(null);
		User user = new User();
		BadayuanNewProxy instance = new BadayuanNewProxy();
		
		user.setAllNum(30);
		user.setCode("362202197609010233");
		user.setPassword("888888");
		user.setZy("5");
		String ip = "123.207.237.42:3128";
		for(int i=10;i<=10;i++) {
			user.setNowNum(i);
			/*for(int n = 0;n<k;n++) {
				String ip = proxy.getOneIpAndPort();
				Map<String,Object> map = instance.listen(user,ip);
				if(map!=null&&"1".equals(map.get("successFlag"))) {
					break;
				}else {
					ipAndPortList.remove(n);
				}
				Thread.sleep(3000);
			}*/
			Thread.sleep(1000);
			Map<String,Object> map = instance.listen(user,ip);
			System.out.println(map.get("msg"));
		}
	}
	
	//统一听课
	public Map<String,Object> listen(User user,String ip){
		this.proxyInfo = ip;
		resultMap = new ConcurrentHashMap<>();
		resultMap.put("successFlag", "0");
		resultMap.put("dayNum", "0");
		resultMap.put("addNum", "0");
		String code = user.getCode();
		if(code==null||code.trim()==""){
			return null;
		}
		try {
			toLoginPage(user);
		} catch (Exception e) {
			printError(user.getZyName()+"-"+ code +"-听"+user.getNowNum()+"/"+user.getTodayNum()+"节听课异常--->",e);
		}
		return resultMap;
	}
	
	/**
	 * 解析登录页，获取登录参数
	 * @param 	loginurl 登录地址
	 * @param	prefixUrl 路径前缀(根路径)
	 */
	private void toLoginPage(User user){
		Map<String,Object> parmsMap = new ConcurrentHashMap<String,Object>();
		String loginUrl = user.getAddress();
		String zy = user.getZy().substring(0,1);
		if(zy.equals("1"))
			user.setIndex("");
		else
			user.setIndex(zy);
		if(loginUrl==null){
			switch(zy){
			case "1": {
				if("10".equals(user.getZy())) {
					user.setZyName("土建施工员");
				}else if("11".equals(user.getZy())) {
					user.setZyName("装饰装修施工员");
				}else if("12".equals(user.getZy())) {
					user.setZyName("设置安装施工员");
				}else if("13".equals(user.getZy())) {
					user.setZyName("市政工程施工员");
				}else {
					log.info("不存在的专业 : " + user.getZy());
					return;
				}
				loginUrl="http://139.199.204.162:8081/Login.aspx?ZY=1";break;
			}
			case "2": {
				user.setZyName("标准员");
				loginUrl="http://139.199.15.78:8081/Login.aspx?ZY=2";break;
			}
			case "3": {
				user.setZyName("材料员");
				loginUrl="http://139.199.64.185:8081/Login.aspx?ZY=3";break;
			}
			case "4": {
				user.setZyName("机械员");
				loginUrl="http://139.199.65.110:8081/Login.aspx?ZY=4";break;
			}
			case "5": {
				user.setZyName("安全员");
				loginUrl="http://139.199.65.98:8081/Login.aspx?ZY=5";break;
			}
			case "6": {
				user.setZyName("资料员");
				loginUrl="http://139.199.65.78:8081/Login.aspx?ZY=6";break;
			}
			case "7": {
				if("70".equals(user.getZy())) {
					user.setZyName("土建质量员");
				}else if("71".equals(user.getZy())) {
					user.setZyName("装饰装修质量员");
				}else if("72".equals(user.getZy())) {
					user.setZyName("设置安装质量员");
				}else if("73".equals(user.getZy())) {
					user.setZyName("市政工程质量员");
				}else {
					log.info("不存在的专业 : " + user.getZy());
					return;
				}
				loginUrl="http://123.207.89.229:8081/Login.aspx?ZY=7";
				break;
			}
			case "8": {
				user.setZyName("劳务员");
				loginUrl="http://139.199.65.78:8082/Login.aspx?ZY=8";
				break;
			}
			}
		}
		String prefixUrl = loginUrl.substring(0,loginUrl.lastIndexOf("/"));
		try {
			response = instance.sendHttpGet(httpClient,loginUrl, proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200 || state ==302){
				Header[] hearders = response.getHeaders("Set-Cookie");
				String loginCookie = hearders[0].getValue();
				String sessionId = loginCookie.substring(0, loginCookie.indexOf(";") + 1);
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
			    Document document = Jsoup.parse(html);
			    Element parm1 = document.getElementById("__VIEWSTATEGENERATOR");
			    String _viewstategenerator = parm1.attr("value");
			    Element parm2 = document.getElementById("__EVENTVALIDATION");
			    String _eventvalidation = parm2.attr("value");
			    Element parm3 = document.getElementById("__VIEWSTATE");
			    String _viewstate = parm3.attr("value");
			    parmsMap.put("_viewstategenerator", _viewstategenerator);
			    parmsMap.put("_eventvalidation", _eventvalidation);
			    parmsMap.put("_viewstate", _viewstate);
			    parmsMap.put("loginUrl",loginUrl);
			    parmsMap.put("prefixUrl",prefixUrl);
			    parmsMap.put("sessionId", sessionId);
			    this.login(parmsMap, user);
			}else{
				print(user.getZyName()+"-"+ user.getCode() +" -自动获取登录页面参数失败!");
			}
		} catch (Exception e) {
			printError(user.getCode()+"-自动获取登录页面参数异常-->",e);
		}finally{
			instance.closeResource(response,httpClient);
		}
	}
	
	//智能听课第三步：智能登录
	public void login(Map<String,Object> parmsMap,User user){
		String se = "";
		String zy = user.getZy();
		String loginUrl = (String) parmsMap.get("loginUrl");
		String code = user.getCode();
		String zyName = user.getZyName();
		String sessionId = (String) parmsMap.get("sessionId");
		if(zy.length()==2){
			se = zy.substring(1);
		}
		Map<String, String> maps = new ConcurrentHashMap<String, String>();
        maps.put("__VIEWSTATE", (String)parmsMap.get("_viewstate")); 
        maps.put("__VIEWSTATEGENERATOR",(String)parmsMap.get("_viewstategenerator"));
        maps.put("__EVENTVALIDATION",(String)parmsMap.get("_eventvalidation")); 
        maps.put("txtUserName",code);
        maps.put("txtPwd",user.getPassword());
        maps.put("ddlType", "2");
        maps.put("btnLogin", "");
        maps.put("txtLoginName", ""); 
        maps.put("txtDM", "");
        maps.put("txtFR", ""); 
        maps.put("zhjg", "");
        maps.put("zhfr", "");
        
        //System.out.println("__VIEWSTATE="+parmsMap.get("_viewstate"));
        //System.out.println("__VIEWSTATEGENERATOR="+parmsMap.get("_viewstategenerator"));
        //System.out.println("__EVENTVALIDATION"+parmsMap.get("_eventvalidation"));
        if(se !=null && !"".equals(se.trim())){
        	maps.put("se", se);
        }
        try {
        	HeadParmsVO head = new HeadParmsVO();
        	head.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        	head.setContentType("application/x-www-form-urlencoded");
        	//head.setDNT("1");
        	head.setCookie(sessionId);
        	head.setUpgradeInsecureRequests("1");
        	head.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
        	response = instance.sendHttpPost(httpClient, head, loginUrl, maps, proxyInfo);
        	if(response==null||response.getStatusLine()==null) {
        		print(zyName +"-"+code+"登录失败，response is null");
        		return;
        	}
        	int state = response.getStatusLine().getStatusCode();
        	System.out.println("login state = "+state);
        	if(state == 200 || state ==302){
        		Header[] hearders = response.getHeaders("Set-Cookie");
        		if(hearders != null && hearders.length > 1) {
        			String userIdCookie = hearders[0].getValue();
        			String userid = userIdCookie.substring(0, userIdCookie.indexOf(";") + 1);
            		String infoCookies = hearders[1].getValue();
            		String info = infoCookies.substring(0, infoCookies.indexOf(";") + 1);
            		//设置登录信息
            		parmsMap.put("userid", userid);
            		parmsMap.put("info", info);
            		//听课
            		shipinSection1(parmsMap,user);
        		}else {
        			print("登录失败！！！"+ zyName +"-"+code+"-Header Set-Cookie 获取异常 -"+hearders.length);
        			logout(parmsMap,user);
        		}
        	}else{
        		print("登录失败！！！当前账户-"+code+"-所选职业为:"+zyName+",请检查职业是否匹配!");
        	}
        	Thread.sleep(1000);
		} catch (Exception e) {
			printError("登录异常,当前账户-"+code+"-所选职业为:"+zyName+"异常信息如下：",e);
		}finally{
			instance.closeResource(response,httpClient);
		}
	}
	
	/**
	 * 第一次shipinSection
	 * */
	public void shipinSection1(Map<String,Object> parmsMap,User user) {
		String prefixUrl = (String) parmsMap.get("prefixUrl");
		String index = user.getIndex();
		String sessionId = (String) parmsMap.get("sessionId");
		String userid = (String) parmsMap.get("userid");
		String info = (String) parmsMap.get("info");
		String openUrl = prefixUrl + "/StudentClass"+ index +"/shipinSection"+ index +".aspx";
		String cookie = sessionId + userid + info;
		HeadParmsVO head = new HeadParmsVO();
		head.setCookie(cookie);
		head.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
		head.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
		user.setCookie(cookie);
		try {
			response = instance.sendHttpGet(httpClient,head,openUrl, proxyInfo);
			if(response==null||response.getStatusLine()==null) {
        		print(user.getZyName()+"-"+user.getCode()+"-第一次shipinSection请求失败，response is null");
        		return;
        	}
			int state = response.getStatusLine().getStatusCode();
			System.out.println("shipinSection1 state = "+state);
			if(state == 200 || state ==302){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
				Document document = Jsoup.parse(html);
				
				Element parm3 = document.getElementById("__VIEWSTATE");
				String __viewstate = parm3.attr("value");
				
				Element parm4 = document.getElementById("__VIEWSTATEGENERATOR");
				String __viewstategenerator = parm4.attr("value");
				
				parmsMap.put("__viewstate", __viewstate);
				parmsMap.put("__viewstategenerator", __viewstategenerator);
				
				checkCanWatch(parmsMap,user);
			}else{
				print("打开听课列表失败！！！当前账户-"+user.getCode()+"-所选职业为:"+user.getZyName()+",请检查职业是否匹配!");
			}
		} catch (Exception e) {
			printError("打开听课列表失败！！！,当前账户-"+user.getCode()+"-所选职业为:"+user.getCode()+"异常信息如下：",e);
		}finally{
			instance.closeResource(response,httpClient);
		}
	}	
		
	//校验是否已听完八节
	public void checkCanWatch(Map<String,Object> parmsMap,User user){
		String index = user.getIndex();
		
		String prefixUrl = (String) parmsMap.get("prefixUrl");
		String code = user.getCode();
		int i = user.getNowNum();
		String id = i <10 ? "0000" + i : "000" + i;
		String vcodeJson = "{Vcode:\"" + id + "\"}";
		String openUrl = prefixUrl + "/StudentClass"+ index +"/shipinSection"+ index +".aspx/CheckCanWatch?dt="+ SpecialCharacterHandler.replaceBlankSpace(DateFormatUtil.getDateEN(new Date()));
		String cookie = user.getCookie();
		HeadParmsVO head = new HeadParmsVO();
		try {
			head.setAccept("application/json, text/javascript");
			head.setAcceptEncoding("gzip, deflate");
			head.setCookie(cookie);
			head.setContentType("application/json; charset=UTF-8");
			head.setxRequestedWith("XMLHttpRequest");
			response = instance.sendHttpPost(httpClient, head, openUrl, vcodeJson, proxyInfo);
			if(response==null||response.getStatusLine()==null) {
        		print(user.getZyName()+"-"+user.getCode()+"-checkCanWatch请求失败，response is null");
        		return;
        	}
			int state = response.getStatusLine().getStatusCode();
			System.out.println("checkCanWatch state ="+state);
			String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
			if(state == 200 || state ==302){
				String msg = (String) JSONObject.fromObject(entityStr).get("d");
				if("".equals(msg)){
					user.setIds(id);
					shipinSection2(parmsMap,user);
				}else{
					resultMap.put("successFlag", "1");
					resultMap.put("dayNum", "1");
					print(user.getZyName() + "-"+code +"-第"+ i +"打开视频播放界面异常："+msg);
				}
			}else{
				print(user.getZyName() + "-"+code +"-第"+ i +"打开视频播放界面失败，状态："+state);
			}
		} catch (Exception e) {
			printError("打开视频播放界面异常,当前账户-"+code+"-所选职业为:"+user.getZyName()+"异常信息如下：",e);
		}finally{
			instance.closeResource(response,httpClient);
		}
	}
	
	/**
	 * 第二次shipinSection
	 * */
	public void  shipinSection2(Map<String,Object> parmsMap,User user){
		String index = user.getIndex();
		String prefixUrl = (String) parmsMap.get("prefixUrl");
		String code = user.getCode();
		String openUrl = prefixUrl + "/StudentClass"+ index +"/shipinSection"+ index +".aspx";
		String cookies = user.getCookie();
		int classNo = user.getNowNum();
		try {
			Map<String, String> maps = new ConcurrentHashMap<String, String>();
	        maps.put("__VIEWSTATE", (String)parmsMap.get("__viewstate")); 
	        maps.put("__VIEWSTATEGENERATOR",(String)parmsMap.get("__viewstategenerator"));
	        maps.put("dr1","-1");
	        for(int k=0;k<10;k++) {
	        	if(classNo <= 10) {
		        	String key = "rep1$ctl0"+ k +"$hdOrders";
		        	maps.put(key, "2");
		        	if(k == classNo)
		        		maps.put("rep1$ctl0"+k+"$Button1", "进入听课");
		        }else if(classNo > 10 && classNo <=20) {
		        	String key = "rep1$ctl"+ (k+10) +"$hdOrders";
		        	maps.put(key, "2");
		        	if(k == classNo)
		        		maps.put("rep1$ctl"+(k+10)+"$Button1", "进入听课");
		        }else if(classNo > 20 && classNo <=30) {
		        	String key = "rep1$ctl"+ (k+20) +"$hdOrders";
		        	maps.put(key, "2");
		        	if(k == classNo)
		        		maps.put("rep1$ctl"+(k+20)+"$Button1", "进入听课");
		        }else {
		        	System.out.println("classNo="+classNo);
		        }
	        }
	        
	        HeadParmsVO head = new HeadParmsVO();
	        head.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
			head.setAcceptEncoding("gzip, deflate");
			head.setCookie(cookies);
			head.setContentType("application/x-www-form-urlencoded");
			response = instance.sendHttpPost(httpClient, head, openUrl, maps, proxyInfo);
			if(response==null||response.getStatusLine()==null) {
        		print(user.getZyName()+"-"+user.getCode()+"-第二次shipinSection请求失败，response is null");
        		return;
        	}
			int state = response.getStatusLine().getStatusCode();
			System.out.println("shipinSection2 state="+state);
			if(state == 200 || state ==302){
				watchVideo(parmsMap,user);
			}else{
				print(user.getZyName() + "-"+code +"-第"+ classNo +"个视频，shipinSection方法请求失败，状态："+state);
			}
		} catch (Exception e) {
			printError("shipinSection异常,当前账户-"+code+"-所选职业为:"+user.getZyName()+"异常信息如下：",e);
		}finally{
			instance.closeResource(response,httpClient);
		}
	}
	
	public void  watchVideo(Map<String,Object> parmsMap,User user){
		String index = user.getIndex();
		String prefixUrl = (String) parmsMap.get("prefixUrl");
		int i = user.getNowNum();
		String ids = user.getIds();
		String id = i < 10 ? "0000" + i : "000" + i;
		String watchUrl = prefixUrl + "/StudentClass"+ index +"/WatchVideo"+ index +".aspx?ids="+ids;
		String cookie = user.getCookie() + " RID="+id +"; id="+id;
		user.setReferer(watchUrl);
		user.setCookie(cookie);
		try {
			HeadParmsVO head = new HeadParmsVO();
			head.setCookie(cookie);
			head.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			response = instance.sendHttpGet(httpClient, head, watchUrl, proxyInfo);
			if(response==null||response.getStatusLine()==null) {
        		print(user.getZyName()+"-"+user.getCode()+"-watchVideo请求失败，response is null");
        		return;
        	}
			int state = response.getStatusLine().getStatusCode();
			System.out.println("watchVideo state="+state);
			if(state == 200){
				saveUpdateInfo(parmsMap,user);
			}else{
				print(user.getZyName() + "-"+user.getCode() +"-第"+ i +"视频，WatchVideo方法请求失败，状态："+state);
			}
		} catch (Exception e) {
			printError("WatchVideo失败,当前账户-"+user.getCode()+"-所选职业为:"+user.getZyName()+"异常信息如下：",e);
		}finally{
			instance.closeResource(response,httpClient);
		}
	}
	
	/**
	 * 保存最后一步更新视频已听课状态的条件
	 * */
	public void saveUpdateInfo(Map<String,Object> parmsMap,User user) {
		Study study = new Study();
		String zy = user.getZy();
		String code = user.getCode();
		int i = user.getNowNum();
		String index = user.getIndex();
		String userid = (String) parmsMap.get("userid");
		String prefixUrl = (String) parmsMap.get("prefixUrl");
		String referer = user.getReferer();
		//设置开始听课时间
		String st = DateFormatUtil.getDateAnyMinuteBeforeFoer8(0);
		st = st.replaceAll(" ", "%20").replaceAll(":", "%3A");
		//构造参数
		int totalTime = getTotalTime(i);
		int nowtime = totalTime - 40;
		String param = "";
		String updateUrl = "";
		String cookie = "";
		try {
			if("5".equals(zy)) {
				//构造请求参数
				String rvCode = i < 10 ? "0000" + i : "000" + i;
				param = "{RVCode:\"" + rvCode + "\"}";
				
				//组装整个cookie
				String url = SpecialCharacterHandler.replaceAll(referer);
				cookie = user.getCookie() +" RID=" + rvCode + "; id="+ rvCode + "; safedog-flow-item=; totaltime="+totalTime+"; url=" + url +"; checkUid="+ userid.split("=")[1] 
							+ " st="+ st +"; PC1=%u6210%u529F; PC2=%u6210%u529F; PC3=%u6210%u529F; PC4=%u6210%u529F; nowtime="+nowtime;
				
				//组装URL
				updateUrl = prefixUrl + "/StudentClass" + index + "/WatchVideo" + index + ".aspx/UpdateStudyType?dt=" + SpecialCharacterHandler.replaceBlankSpace(DateFormatUtil.getDateEN(new Date()));
			}else {
				//构造请求参数
				int num = getRvCodeJson(i);
				param = "{RVCode:\"" + num + "\"}";
				
				//组装整个cookie
				String url = SpecialCharacterHandler.replaceAll(referer);
				cookie = user.getCookie() + "; url=" + url + "; checkUid=" + userid.split("=")[1] +" st="+ st +";totaltime="+totalTime +"; nowtime="+nowtime;
				
				//组装URL
				updateUrl = prefixUrl + "/StudentClass" + index + "/WatchVideo" + index + ".aspx/UpdateStudyType?dt=" + SpecialCharacterHandler.replaceBlankSpace(DateFormatUtil.getDateEN(new Date()));
			}
			System.out.println(cookie);
			System.out.println(updateUrl);
			System.out.println(param);
			study.setCode(user.getCode());
			study.setCookie(cookie);
			study.setUrl(updateUrl);
			study.setCreateTime(new Date());
			study.setParams(param);
			study.setSuccessFlag(0);
			study.setNum(i);
			study.setZyName(user.getZyName());
			resultMap.put("study", study);
			print(user.getZyName() +"-"+ code +"-第" +i +"个视频保存听课信息成功");
			Thread.sleep(1000);
		} catch (Exception e) {
			printError(user.getZyName() +"-"+ code +"-第" +i +"个视频保存听课信息失败--->",e);
		}finally{
			instance.closeResource(response,httpClient);
		}
	}
	
	public Map<String,Object> updateStudyVideo(Study study,String ip){
		resultMap = new ConcurrentHashMap<>();
		resultMap.put("successFlag", "0");
		resultMap.put("dayNum", "0");
		resultMap.put("addNum", "0");
		String code = study.getCode();
		String rvCodeJson = "{RVCode:\"00010\"}";
		String cookie = "ASP.NET_SessionId=0kwngb5yxvk1qpfjix1gwy1q;userid=126807;info=name=%e5%be%90%e6%9d%83%e5%8d%8e; RID=00010; id=00010 RID=00010; id=00010; safedog-flow-item=; totaltime=2418; url=http%3A//139.199.65.98%3A8081/StudentClass5/WatchVideo5.aspx%3Fids%3D00010; checkUid=126807; st=2018/9/25%2016%3A52%3A48; PC1=%u6210%u529F; PC2=%u6210%u529F; PC3=%u6210%u529F; PC4=%u6210%u529F; nowtime=2378";
		String updateUrl = "http://139.199.65.98:8081/StudentClass5/WatchVideo5.aspx/UpdateStudyType?dt=Tue%20Sep%2025%202018";
		int num = study.getNum();
		HeadParmsVO head = new HeadParmsVO();
		head.setAccept("application/json, text/javascript, */*; q=0.01");
		head.setAcceptEncoding("gzip, deflate");
		head.setContentType("application/json; charset=UTF-8");
		head.setCookie(cookie);
		head.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
		head.setxRequestedWith("XMLHttpRequest");
		try {
			response = instance.sendHttpPost(httpClient, head, updateUrl, rvCodeJson, ip);
			if(response==null||response.getStatusLine()==null) {
        		print(study.getZyName()+"-"+study.getCode()+"-updateStudyVideo请求失败，response is null");
        		return resultMap;
        	}
			int state = response.getStatusLine().getStatusCode();
			String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
			if(state == 200 || state ==302){
				String msg = (String) JSONObject.fromObject(entityStr).get("d");
				print(study.getZyName() + "-"+code +"-第"+ (num+1) +"个视频"+msg);
				resultMap.put("successFlag", "1");
				if("进度更新完毕，请看下个视频".equals(msg)){
					resultMap.put("dayNum", "1");
					resultMap.put("addNum", "1");
				}else if("本视频播放完毕".equals(msg)){
					resultMap.put("addNum", "1");
				}else if("课程全部看完，可以进行考试".equals(msg)){//听完最后一个修改状态为已完成
					study.setState(2);
				}else{
 				}
			}else{
				print("updateStudyVideo-"+study.getZyName() + "-"+code +"-第"+ num +"个视频播放失败,state="+state);
			}
		} catch (Exception e) {
			print("updateStudyVideo-"+study.getZyName() + "-"+code +"-第"+ num +"个视频播放异常"+e);
		}finally{
			instance.closeResource(response,httpClient);
			logout(study,ip);
		}
		return resultMap;
	}
	
	public void logout(Study study,String ip){
		String loginUrl = study.getPrefixUrl();
		String prefixUrl = loginUrl.substring(0,loginUrl.lastIndexOf("/"));
		String zyName = study.getZyName();
		String zy = StringUtil.getZyByName(zyName);
		String code = study.getCode();
		String ck = study.getCookie();
		String cookie = ck.substring(0, ck.indexOf("url"));
		HeadParmsVO heads = new HeadParmsVO();
		try {
			heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			heads.setCookie(cookie);
			String path = prefixUrl+"/Public/Logout.aspx?id="+zy;
			response = instance.sendHttpGet(httpClient, heads, path, ip);
			if(response==null||response.getStatusLine()==null) {
        		print(study.getZyName()+"-"+study.getCode()+"-updateStudyVideo请求失败，response is null");
        		return ;
        	}
			int state = response.getStatusLine().getStatusCode();
			if(state == 200 || state == 302){
				//log.info(zyName+"-"+code+"-退出登录成功!");
			}else{
				//log.info(zyName+"-"+code+"-退出登录失败!");
			}
		} catch (Exception e) {
			printError(zyName+code+"退出登录错误--->",e);
		}finally{
			instance.closeResource(response, httpClient);
		}
	}
	
	public void logout(Map<String,Object> parmsMap,User user){
		String prefixUrl = (String) parmsMap.get("prefixUrl");
		String zy = user.getZy();
		String zyName = user.getZyName();
		String code = user.getCode();
		String sessionId = (String) parmsMap.get("sessionId");
		String userid = (String) parmsMap.get("userid");
		String info = (String) parmsMap.get("info");
		HeadParmsVO heads = new HeadParmsVO();
		try {
			String path = prefixUrl+"/Public/Logout.aspx?id="+zy;
			String cookie = sessionId + userid + info +" totaltime=2281; checkUid="+userid+"; nowtime=2281";
			heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			heads.setCookie(cookie);
			response = instance.sendHttpGet(httpClient, heads, path, proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200 || state == 302){
				log.info(zyName+"-"+code+"-退出登录成功!");
			}else{
				log.info(zyName+"-"+code+"-退出登录失败!");
			}
		} catch (Exception e) {
			printError(zyName+code+"退出登录错误--->",e);
		}finally{
			instance.closeResource(response, httpClient);
		}
	}

	private void print(String msg){
		resultMap.put("msg", msg);
		//log.info(msg);
	}
	
	private int getTotalTime(int i) {
		switch(i){
			case 1:return 2458;
			case 2:return 2318;
			case 3:return 2349;
			case 4:return 2421;
			case 5:return 2409;
			case 6:return 2367;
			case 7:return 2281;
			case 8:return 2483;
			case 9:return 2417;
			case 10:return 2418;
			case 11:return 2324;
			default : return 2458;
		}
	}
	
	public int getRvCodeJson(int i){
		if(i < 10 || i==18 || i==19 || i==28 || i==29)
			return i;
		else if (i >= 10 && i <= 17)
			return i-2;
		else if(i==30)
			return i - 6;
		else if(i >= 20 || i <= 27)
			return i-4;
		else
			return i;
	}
	
	private void printError(String msg,Exception e){
		msg = msg + e.getMessage();
		resultMap.put("errorMsg", msg);
		log.info(msg,e);
	}
}
